package com.zxq.common.utils.internal.http;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @Author: tangzhi
 * @Description:
 * @Date: 2021/2/4
 */
public class DefaultRetryIntercepter implements Interceptor {

    /**
     * 最大重试次数
     */
    private int maxRetryTimes;

    /**
     * 重试次数，假如设置为3次重试的话，则最大可能请求4次（默认1次+3次重试）
     */
    private int retryTimes = 0;

    public DefaultRetryIntercepter(int maxRetryTimes) {
        this.maxRetryTimes = maxRetryTimes;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        Response response = chain.proceed(request);
        while (!response.isSuccessful() && retryTimes < maxRetryTimes) {
            response.close();
            retryTimes++;
            response = chain.proceed(request);
        }
        return response;
    }
}
